package org.smart4j.framework.util;

import org.apache.commons.lang3.StringUtils;

/**
 * Created by Lin on 2018/03/29.
 */
public final class CastUtil {

    public static String castString(Object obj) {
        return castString(obj, "");
    }

    /** 转为String值（提供默认值） */
    public static String castString(Object obj, String defaultValue) {
        return obj != null ? obj.toString() : defaultValue;
    }

    public static int castInt(Object obj){
        return castInt(obj, 0);
    }

    /** 转为int值（提供默认值）*/
    public static int castInt(Object obj, int defaultValue) {
        int value = defaultValue;
        if(obj == null) {
            return value;
        }

        String strValue = castString(obj);
        if(StringUtils.isEmpty(strValue)) {
            return value;
        }
        try {
            value = Integer.parseInt(strValue);
        } catch (NumberFormatException e) {
            value = defaultValue;
        }
        return value;
    }
}
